package org.flown.shop.service;

import org.flown.shop.dao.UserDAO;
import org.flown.shop.dto.UserDTO;
import org.flown.shop.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * UserService
 * UserDAO
 * */
@Service
public class UserService extends BaseService<User>
{
    private final UserDAO dao_user;

    @Autowired
    public UserService(UserDAO dao_user) {
        super(dao_user);
        this.dao_user = (UserDAO) this.dao;

    }


    private User getUserByID(int id) {return this.selectByID(id);}
    public UserDTO getUserDTOByID(int id) {return new UserDTO(this.selectByID(id));}


    /**
     * username
     * password
     * */
    public int insertUser(User user)
    {
        if (this.getUserByUsername(user.getUsername()) != null)
            return 0;
        return this.insert(user);
    }
    public boolean updateUserByID(User original_user) {return this.updateByID(original_user);}
    public int deleteUserByID(int id) {return this.deleteByID(id);}


    private User getUserByUsername(String username) {return this.dao_user.selectByUsername(username);}
    public UserDTO getUserDTOByUserName(String username) {return new UserDTO(this.dao_user.selectByUsername(username));}


    public ServiceResult register(String nickname, String username, String password)
    {
        if (this.getUserByUsername(username) != null) {
            System.out.println(this + ".register: 用户已存在");
            return ServiceResult.EXISTS;
        }

        if (this.insertUser(new User(nickname, username, password)) == 0)
            return ServiceResult.FAILED;
        
        System.out.println(this + ".register: 注册成功");
        return ServiceResult.SUCCESS;
    }


    public ServiceResult login(String username, String password)
    {
        User user = this.getUserByUsername(username);
        if (user == null)
        {
            System.out.println(this + ".login: 用户不存在");
            return ServiceResult.NOT_EXISTS;
        }

        if (user.getPassword().equals(password))
        {
            System.out.println(this + ".login: 登陆成功");
            return ServiceResult.SUCCESS;
        }

        System.out.println(this + ".login: 密码错误");
        return ServiceResult.FAILED;
    }


}




